import {
  PlusOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import { Button, Tag, Tooltip, Rate, message } from 'antd';
import React, { useRef } from 'react';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormGroup,
  ProFormList,
  ProFormDependency,
} from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-components';
import moment from 'moment';
import { useRequest } from 'umi';

export default () => {
  const editTaskRef = useRef<ProFormInstance>();

  //新建任务
  const publishTask = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/publishTask`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //导师端——获取自己学生的任务
  const getUnderStuTask = useRequest((data = {}) => {
    let url = '';
    let count = 0;
    Object.keys(data).map((value: any, index: any) => {
      // console.log(value);
      let key_temp = value;
      let value_temp = data[value];
      if (data[value]) {
        if (count == 0) {
          url = url + '?' + key_temp + '=' + value_temp;
        } else {
          url = url + '&' + key_temp + '=' + value_temp;
        }
        count++;
      }
    });
    return {
      url: `http://10.1.40.84:9998/stuTrain/getUnderStuTask` + url,
      method: 'GET',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
    };
  });

  //学生端——获取任务详细
  const getMyOneTask = useRequest(
    (id = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getMyOneTask?id=${id}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );

  const taskColumns = [
    {
      title: '任务名称',
      dataIndex: 'taskName',
      key: 'taskName',
      hideInSearch: true,
    },
    {
      title: '任务简介',
      dataIndex: 'taskDesc',
      key: 'taskDesc',
      hideInSearch: true,
      // render: (text: any) => <Tag color={'blue'}>{text}</Tag>,
    },
    {
      title: '任务状态',
      dataIndex: 'recvState',
      key: 'recvState',
      hideInSearch: true,
      render: (text: any) => {
        if (text === '0') {
          return (
            <Tag icon={<ClockCircleOutlined />} color="default">
              未读
            </Tag>
          );
        } else if (text === '1') {
          return (
            <Tag icon={<SyncOutlined spin />} color={'processing'}>
              进行中
            </Tag>
          );
        } else {
          return (
            <Tag icon={<CheckCircleOutlined />} color="success">
              已完成
            </Tag>
          );
        }
      },
    },
    {
      title: '学生姓名',
      dataIndex: 'stuName',
      key: 'stuName',
    },
    {
      title: '任务开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      hideInSearch: true,
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },
    {
      title: '任务结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      hideInSearch: true,
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },

    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      align: 'center',
      render: (text: any, record: any) => [
        <ModalForm
          key="1"
          title={record?.taskName || '任务详情'}
          trigger={
            <a
              onClick={() => {
                getMyOneTask.run(record.id).then((e) => {
                  editTaskRef.current?.setFieldsValue(e);
                  getUnderStuTask.run();
                });
              }}
            >
              查看任务
            </a>
          }
          autoFocusFirstInput
          modalProps={{
            onCancel: () => console.log('run'),
            destroyOnClose: true,
          }}
          submitTimeout={2000}
          // onFinish={async (values) => {
          //   await waitTime(2000);
          //   updateMyTask.run({
          //     ...getMyOneTask?.data,
          //     materialList: values.materialList,
          //   });
          //   return true;
          // }}
          submitter={false}
          formRef={editTaskRef}
          // width={800}
        >
          <ProForm.Group>
            <ProFormText width="md" name="taskName" label="任务名称" disabled />
            <ProFormText width="md" name="taskDesc" label="任务简述" disabled />
            <ProFormDatePicker
              width="md"
              name="startTime"
              label="开始时间"
              disabled
            />
            <ProFormDatePicker
              width="md"
              name="endTime"
              label="结束时间"
              disabled
            />
          </ProForm.Group>
          <ProFormList
            name="materialList"
            label="材料信息"
            rules={[
              {
                validator: async (_, value) => {
                  // console.log(value);
                  if (value && value.length > 0) {
                    return;
                  }
                  throw new Error('至少要有一项！');
                },
              },
            ]}
            creatorButtonProps={{
              creatorButtonText: '添加材料',
              hidden: true,
            }}
            copyIconProps={
              record.recvState === '2' ? false : { tooltipText: '复制' }
            }
            deleteIconProps={
              record.recvState === '2' ? false : { tooltipText: '删除' }
            }
          >
            {(meta: any, index: any, action: any, count: any) => {
              return (
                <ProFormGroup key="group">
                  <ProFormText
                    width="sm"
                    required
                    name="materialName"
                    label="材料名称"
                    disabled={record.recvState === '2'}
                  />
                  <ProFormSelect
                    label="材料类型"
                    name="materialType"
                    width="xs"
                    required
                    disabled={record.recvState === '2'}
                    valueEnum={{
                      学习报告: '学习报告',
                      参考文献: '参考文献',
                    }}
                  />
                  <ProFormDependency name={['materialType']}>
                    {({ materialType }) => {
                      if (materialType === '参考文献') {
                        return (
                          <ProFormText
                            width="sm"
                            name="materialContent"
                            label="文献链接"
                            required
                          />
                        );
                      } else if (
                        materialType === '学习报告' ||
                        materialType === '阶段性报告'
                      ) {
                        return (
                          <ProFormText
                            width="sm"
                            name="materialContent"
                            required
                            hidden
                          />
                        );
                      } else {
                        return null;
                      }
                    }}
                  </ProFormDependency>
                  <ProFormDependency name={['materialType']}>
                    {({ materialType }) => {
                      if (
                        materialType === '学习报告' &&
                        action.getCurrentRowData().materialContent
                      ) {
                        return (
                          <Button
                            type={'link'}
                            style={
                              index === 0 ? { marginTop: 30 } : { marginTop: 0 }
                            }
                            onClick={() => {
                              window.open(
                                action.getCurrentRowData().materialContent,
                              );
                            }}
                          >
                            下载
                          </Button>
                        );
                      } else {
                        return null;
                      }
                    }}
                  </ProFormDependency>
                </ProFormGroup>
              );
            }}
          </ProFormList>
        </ModalForm>,
      ],
    },
  ];

  return (
    <ProTable
      columns={taskColumns}
      dataSource={getUnderStuTask?.data || []}
      rowKey="id"
      pagination={{
        showQuickJumper: true,
      }}
      dateFormatter="string"
      headerTitle="任务列表"
      options={false}
      onSubmit={(e) => getUnderStuTask.run(e)}
      onReset={() => getUnderStuTask.run()}
      toolBarRender={() => [
        <ModalForm
          title="新建任务"
          trigger={
            <Button type="primary" style={{ marginRight: 10 }}>
              {/* <PlusOutlined /> */}
              新建任务
            </Button>
          }
          autoFocusFirstInput
          modalProps={{
            onCancel: () => console.log('run'),
          }}
          submitTimeout={2000}
          onFinish={async (values) => {
            // await waitTime(2000);
            publishTask.run(values).then(() => {
              getUnderStuTask.run();
              message.success('提交成功');
            });
            return true;
          }}
        >
          <ProForm.Group>
            <ProFormText width="md" name="taskName" label="任务名称" required />
            <ProFormText width="md" name="taskDesc" label="任务简介" required />
            <ProFormDatePicker
              width="md"
              name="startTime"
              label="计划开始时间"
              required
            />
            <ProFormDatePicker
              width="md"
              name="endTime"
              label="计划终止时间"
              required
            />

            <ProFormSelect
              width="xl"
              options={[
                {
                  value: 1111,
                  label: '董思纶',
                },
                {
                  value: 2222,
                  label: '曹嘉玺',
                },

                {
                  value: 3333,
                  label: '李靖涵',
                },
                {
                  value: 4444,
                  label: '张方明',
                },
                {
                  value: 5555,
                  label: '金建铭',
                },
                {
                  value: 6666,
                  label: '曹嘉玺',
                },
                {
                  value: 7777,
                  label: '许瑞波',
                },
                {
                  value: 8888,
                  label: '张鑫',
                },
                {
                  value: 9999,
                  label: '郭睿哲',
                },
              ]}
              name="stuIds"
              label="目标学生"
              mode="multiple"
              required
            />
          </ProForm.Group>
        </ModalForm>,
      ]}
    />
  );
};
